function [minmaxbox] = minmaxbbox(varargin)
% minmaxbbox  - get minimum, maximum bounding box of objects
%
% FORMAT:       minmaxbox = minmaxbbox(v, ...)
%
% Input fields:
%
%       v           either 1x1 VMR or VTC object or cell array
%       ...         further objects
%
% Output fields:
%
%       minmaxbox   4x3 array with minimum (intersect) and
%                   maximum (union) bounding box of objects
%                   valid for .Reframe calls
%
% Note: if all input objects are V16, is returned in natural resolution

% Version:  v0.7a
% Build:    7082312
% Date:     Aug-23 2007, 12:54 PM CEST
% Author:   Jochen Weber, Brain Innovation, B.V., Maastricht, NL
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin == 0 || ...
    isempty(varargin{1}) || ...
   (~iscell(varargin{1}) && ...
    ~isBVQXfile(varargin{1}(1), true)) || ...
   (iscell(varargin{1}) && ...
    ~isBVQXfile(varargin{1}{1}(1), true))
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end
tcc = 0;
for ac = 1:nargin
    if ~iscell(varargin{ac})
        varargin{ac} = {varargin{ac}};
    end
    for cc = 1:numel(varargin{ac})
        if numel(varargin{ac}{cc}) ~= 1 || ...
           ~isBVQXfile(varargin{ac}{cc}, true)
            error( ...
                'BVQXtools:BadArgument', ...
                'Bad argument.' ...
            );
        end
    end
    tcc = tcc + numel(varargin{ac});
end
oc = cell(1, tcc);
tcc = 0;
for ac = 1:nargin
    oc((tcc + 1):(tcc + numel(varargin{ac}))) = varargin{ac}(:);
    tcc = tcc + numel(varargin{ac});
end

% check each type
for cc = tcc:-1:1
    
    % allowed are AVA/CMP/DDT/GLM/MSK/VDW/VMR/VMP/VTC
    if ~any(strcmpi(oc{cc}.Filetype, ...
         {'ava', 'cmp', 'ddt', 'glm', 'msk', 'vdw', 'vmp', 'vmr', 'vtc'}))
        oc(cc) = [];
    end
end

% reject empty array
if isempty(oc)
    error( ...
        'BVQXtools:BadArgument', ...
        'None of the supported types passed in.' ...
    );
end

% start with first
res = zeros(tcc, 3);
fc = oc{1}.BoundingBox.FCube;
minmaxbox = repmat([0, fc(1), fc(1), 0]', [1, 3]);

% iterate from 2 to last
for cc = 1:tcc
    bbox = oc{cc}.BoundingBox;
    nbox = bbox.BBox;
    minmaxbox([1, 4], :) = max(minmaxbox([1, 4], :), nbox);
    minmaxbox([3, 2], :) = min(minmaxbox([3, 2], :), nbox);
    res(cc, :) = bbox.ResXYZ;
end

% check resolution
if ~all(all(res == res(1)))
    error( ...
        'BVQXtools:BadArgument', ...
        'Files must match in dimension.' ...
    );
end
